module.exports = {
  APIError: function (code, message, status = 200) {
    this.code = code || "internal: unknown_error";
    this.message = message || "";
    this.status = status;
  },
  restify: (pathPrefix) => {
    // REST API前缀，默认为/api/:
    pathPrefix = pathPrefix || "/api/";
    return async (ctx, next) => {
      let { request: req, response: res } = ctx;
      // 是否是REST API前缀?
      if (req.path.startsWith(pathPrefix)) {
        // 绑定rest()方法:
        ctx.rest = (data, info = {}) => {
          res.type = "application/json";
          res.body = {
            code: "request_ok",
            data: data || null,
            message: info.message || "Success",
          };
        };
        try {
          await next();
        } catch (e) {
          // 返回错误:
          res.status = e.status || 400;
          res.type = "application/json";
          e.code = e.status === 401 ? "authentication: error" : e.code;
          res.body = {
            code: e.code || "internal: unknown_error",
            message: e.message || "Error",
          };
        }
      } else {
        await next();
      }
    };
  },
};
